import el from '../main'
import fetchJsonp from "fetch-jsonp";
import api from '../api/api.js';
import { $getad } from '../api/http.js'
import moment from 'moment';
var addressHandler = function (data) {
    console.log(data)
};
/**
 * 省市区
 * @param {*} level  省市区等级
 * @param {*} parentid 上级id
 */
export function getAddressList(level, parentid) {
    let addrList = [];
    return new Promise((reslove, reject) => {
        // console.log(api.getAddress)
        // #ifdef  MP-WEIXIN
        $getad(api.getAddress, { level: level, parent: parentid, callback: 'addressHandler' }).then((res) => {
            let data = JSON.parse(res.slice(15, res.length - 1));
            if (data.Success) {
                data.ObjectValue.forEach(item => {
                    let addrItem = new Object;
                    addrItem.key = item.ID;
                    addrItem.value = item.Name;
                    addrItem.LevelNum = item.LevelNum;
                    addrItem.ParentID = item.ParentID;
                    addrList.push(addrItem)
                })
                reslove(addrList)
            } else {
                reject(false)
            }

        })
        // #endif
        // #ifdef  H5
        let url = `${api.getAddress}&level=${level}&parent=${parentid}`;
        fetchJsonp(url).then(res => {
            res.json().then((json) => {
                console.log(json);
                if (json.Success) {
                    json.ObjectValue.forEach(item => {
                        let addrItem = new Object;
                        addrItem.key = item.ID;
                        addrItem.value = item.Name;
                        addrItem.LevelNum = item.LevelNum;
                        addrItem.ParentID = item.ParentID;
                        addrList.push(addrItem)
                    })
                    reslove(addrList)
                } else {
                    reject(false)
                    // el.$toast("前方拥堵，稍后在来")
                }
            })
        })
        // #endif
    }).catch((e) => { })
}
/**
 * 
 * @param {*} time 默认2s 设置为0则不会消失  设置为1则隐藏
 */
export function loading(time = 2000, txt = "loading...") {
    const toast = el.$createToast({
        txt: txt,
        mask: true,
        time: time,
    })
    toast.show()
}

//时间的对比  依次传入结束时间，开始时间（不传默认为今天），返回时间单位（years，months，days，minutes，seconds）默认为days
export function compareTime(endTime, startTime = new Date(), timeType = "days") {
    var type
    switch (timeType) {
        case "years": 
            type = "年"
            break;
        case "months": 
            type = "月"
            break;
        case "days": 
            type = "天"
            break;
        case "minutes": 
            type = "分钟"
            break;
        case "seconds": 
            type = "秒"
            break;
    }
    return (-moment(startTime).diff(moment(endTime), timeType) +type)
}

//判断是否String
export function isString(str) {
    return ((str instanceof String) || (typeof str).toLowerCase() == 'string');
}

//随机数生成，传入随机数区间
export function randomRange(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

//关闭微信浏览器
export function closeWindow() {
    wx.closeWindow();
}
//手机号中间4位加密
export function encryptionMob(val) {
    let reg = /^(\d{3})\d{4}(\d{4})$/;
    let newVal = val.replace(reg, '$1****$2');
    return newVal;
}
//积分三位加逗号
export function formatAmount(val) {
    var newVal = parseInt(val).toString();
    var len = newVal.length;
    if (len <= 3) { return newVal; }
    var r = len % 3;
    return r > 0 ? newVal.slice(0, r) + "," + newVal.slice(r, len).match(/\d{3}/g).join(",") : newVal.slice(r, len).match(/\d{3}/g).join(",");
}


//防抖
export function debounce(fn, delay = 2000) {
    let timer = null;
    return function (a, b) {
        let args = arguments;
        if (timer) return
        fn.apply(this, args);
        timer = setTimeout(function () {
            timer = null
            clearTimeout(timer)
        }, delay);
    }
}
//微信预览图片
export function showBigPic(img) {
    wx.previewImage({
        current: img,//当前显示图片的http链接
        urls: [img] //需要预览的图片http链接列表
    })
}
//节流
export function throttle(fn, delay = 2000) {
    var timer
    var _self = fn
    return function () {
        clearTimeout(timer)
        var args = arguments
        var _me = this
        timer = setTimeout(function () {
            _self.apply(_me, args)
        }, delay)
    }
}

// 获取路径的query参数
export function getParams(name) {
    const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    let r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}
//获取路径中的参数
export function getParamsBydecodeURI(name) {
    let result = (window.location.search + window.location.hash).match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
    if (result == null || result.length < 1) {
        return "";
    }
    return result[1];
}
//获取哈希路径中的参数
export function getHashData(name) {
    var result = window.location.hash.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
    if (result == null || result.length < 1) {
        return "";
    }
    return result[1].split('#')[0];
}
//密码校验
export function isPasswd(s) {
    var patrn = /^(\w){6,20}$/;
    if (!patrn.exec(s)) return false;
    return true
}
//手机号码
export function isPhone(s) {
    var patrn = /^(?:13\d|14\d|15\d|16\d|17\d|19\d|18\d)\d{5}(\d{3}|\*{3})$/;
    if (!patrn.exec(s)) return false;
    return true
}

//强制滚动
export function wrapper(id, isHideScrollBar = true) {
    var myScroll = new iScroll(id, {
        checkDOMChanges: true,
        vScrollbar: isHideScrollBar,
        click: true,
        scrollX: false,
        preventDefault: false,
        hideScrollbar: !isHideScrollBar,
        hScroll: false,
        hscrollbar: false
    });
}
//input失焦滚动
export function scrollToTop() {
    (function smoothscroll() {
        let currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
        if (currentScroll > 0) {
            window.requestAnimationFrame(smoothscroll);
            window.scrollTo(0, currentScroll - (currentScroll / 5));
        }
    })();
}

//input失焦窗口滚动
export function scrollToEl(el) {
    el.scrollIntoView({ behavior: "smooth", block: "start" })
    let ls, speed;
    (function smoothscroll() {
        let currentScroll = el.offsetTop;
        let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        if (currentScroll != scrollTop && ls != scrollTop) {
            if (!speed) speed = Math.floor(currentScroll / 50)
            ls = scrollTop
            window.scroll(0, scrollTop + Math.floor((currentScroll - scrollTop) / speed));
            window.requestAnimationFrame(smoothscroll);
        }
    })();
}
//input失焦窗口滚动
export function changeBlur() {
    let u = navigator.userAgent, app = navigator.appVersion;
    let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
    if (isIOS) {
        let timer = setTimeout(() => {
            const scrollHeight = document.documentElement.scrollTop || document.body.scrollTop || 0
            window.scrollTo(0, Math.max(scrollHeight - 1, 0))
            clearTimeout(timer)
        }, 200)
    }
}


//深拷贝
export function deepCopy(obj) {
    let result = obj instanceof Array ? [] : {}
    let keys = Object.keys(obj), key = null, temp = null;
    for (let i = 0; i < keys.length; i++) {
        key = keys[i]
        temp = obj[key]
        if (temp && typeof temp === 'object') {
            if (temp != obj) {  // 解决堆栈溢出
                result[key] = deepCopy(temp)
            }
        } else {
            result[key] = temp
        }
    }
    return result;
}





function formatNumber(n) {
    const str = n.toString()
    return str[1] ? str : `0${str}`
}
//时间格式化
export function formatTime(date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()

    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    const t1 = [year, month, day].map(formatNumber).join('/')
    const t2 = [hour, minute, second].map(formatNumber).join(':')

    return `${t1} ${t2}`
}

//解析路径
export function GetRequestData() {
    var url = location.search;
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
        }
    }
    return theRequest;
};

//   export default {
//     formatNumber,
//     formatTime
//   }





